package com.onec.service.unsafe.lock;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Semaphore;
import java.util.concurrent.atomic.AtomicInteger;

public class SemaphoreDemo {

    public void testShareLock() {
        final CountDownLatch countDownLatch = new CountDownLatch(10);
        final Semaphore semaphore = new Semaphore(2);

        AtomicInteger atomicInteger = new AtomicInteger(0);

        Runnable r = () -> {
            try {
                semaphore.acquire(1);
                // do something
                Thread.sleep(1000);
                semaphore.release();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            countDownLatch.countDown();
        };

        Thread[] threads = new Thread[10];
        for (int i = 0; i < 10; i++) {
            threads[i] = new Thread("xian" + i);
        }
        for (int i = 0; i < 10; i++) {
            threads[i].start();
        }
        try {
            countDownLatch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }



}
